﻿namespace Chain.Tasks
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Xml;

    public class TaskThread : IDisposable
    {
        private bool _disposed;
        private bool _isRunning;
        public readonly int _seconds;
        private DateTime _started;
        public readonly Dictionary<string, Task> _tasks;
        private Timer _timer;

        public TaskThread()
        {
            this._tasks = new Dictionary<string, Task>();
            this._seconds = 600;
        }

        public TaskThread(XmlNode node)
        {
            this._tasks = new Dictionary<string, Task>();
            this._seconds = 600;
            this._isRunning = false;
            if ((node.Attributes["seconds"] != null) && !int.TryParse(node.Attributes["seconds"].Value, out this._seconds))
            {
                this._seconds = 600;
            }
        }

        public void AddTask(Task task)
        {
            if (!this._tasks.ContainsKey(task.Name))
            {
                this._tasks.Add(task.Name, task);
            }
        }

        public void Dispose()
        {
            if ((this._timer != null) && !this._disposed)
            {
                lock (this)
                {
                    this._timer.Dispose();
                    this._timer = null;
                    this._disposed = true;
                }
            }
        }

        public void InitTimer()
        {
            if (this._timer == null)
            {
                this._timer = new Timer(new TimerCallback(this.TimerHandler), null, this.Interval, this.Interval);
            }
        }

        private void Run()
        {
            this._started = DateTime.Now;
            this._isRunning = true;
            foreach (Task task in this._tasks.Values)
            {
                task.Execute();
            }
            this._isRunning = false;
        }

        private void TimerHandler(object state)
        {
            this._timer.Change(-1, -1);
            this.Run();
            this._timer.Change(this.Interval, this.Interval);
        }

        public int Interval
        {
            get
            {
                return (this._seconds * 0x3e8);
            }
        }
    }
}

